package com.baor.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    //存储单值
    public void setValue(String key,Object value){
        redisTemplate.opsForValue().set(key,value);
    }

    public Object getValue(String key){
        return redisTemplate.opsForValue().get(key);
    }
    //验证是否存在key
    public boolean containsKey(String key){
        return redisTemplate.hasKey(key);
    }
    //删除key
    public boolean delKey(String key){
        return redisTemplate.delete(key);
    }
    //存储列表
    public <T>void setList(String key,List<T> list){
        list.forEach(x -> redisTemplate.opsForList().rightPush(key,x));
    }
    //遍历列表
    public <T>List<T> getList(String key,long start,long end){
        List<T> range = redisTemplate.opsForList().range(key, start, end - 1);
        return range;
    }
    //遍历列表
    public <T>List<T> getList(String key){
        List<T> range = redisTemplate.opsForList().range(key, 0, getListSize(key) - 1);
        return range;
    }

    //获取列表总数量
    public long getListSize(String key){
        return this.redisTemplate.opsForList().size(key);
    }
    //存储set
    public <T> void setSet(String key, Set<T> set){
        set.forEach(x -> redisTemplate.opsForSet().add(key, x));
    }
    //获取set
    public <T>Set<T> getSet(String key){
        return redisTemplate.opsForSet().members(key);
    }
    //获取size
    public long getSetSize(String key){
        return redisTemplate.opsForSet().size(key);
    }
    //存储hash
    public void setHash(String key, Map<String,Object> params){
        params.forEach((k,v) ->  this.redisTemplate.opsForHash().put(key,k,v));
    }
    //获取k-v集合
    public <T>Map<String,T> getHash(String key){
        return this.redisTemplate.opsForHash().entries(key);
    }
    //获取Hash长度
    public long getHashSize(String key){
        return this.redisTemplate.opsForHash().size(key);
    }
    // 示例：设置 30s 过期
    public Boolean setTokenExpiry(String key) {
        return redisTemplate.expire(key, 10, TimeUnit.SECONDS);
    }
    /**
     * 获取 key 的剩余生存时间（秒）
     */
    public Long getTTL(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

}
